package com.fingard.dsp.bank.directbank.spdb01;

import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.IReceipt;
import com.fingard.dsp.bank.helpers.DataFileHelper;
import com.fingard.dsp.bank.helpers.ReceiptFileSaveHelper;
import com.fingard.dsp.bank.reqrespobj.downloadreceipt.ReqQryReceipt;
import com.fingard.dsp.bank.reqrespobj.downloadreceipt.RetAtsReceipt;
import com.fingard.io.FileHelper;
import com.fingard.text.StringHelper;
import com.fingard.util.PdfGenerateUtil;
import com.fingard.util.SmbFileUtil;
import com.fingard.util.ZipHelper;

import java.io.File;
import java.util.Calendar;
import java.util.Date;

/**
 * Created by shenqi on 2019/6/20.
 */
public class SPDB01Receipt extends SPDB01Base implements IReceipt {
    @Override
    public RetAtsReceipt qryReceipt(ReqQryReceipt p_reqReceipt) throws Exception {
        RetAtsReceipt retAts = new RetAtsReceipt(p_reqReceipt.reqHeader);
        try {
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_reqReceipt.getDateFrom());
            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_reqReceipt.getDateTo());
            int tmpIntFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
            int tmpIntTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
            StringBuilder json = new StringBuilder();
            if (getBankConfig().getValueAsBool("receiptPushHasTenantId")) {
                json.append("tenantId=" + FGBiz.dspCenter.dspSet.tenant + "&transType=downloadreceipt&data={\"rows\":[");
            } else {
                json.append("transType=downloadreceipt&data={\"rows\":[");
            }
            //boolean receiptUploadShared = this.getBankConfig().getValueAsBool("receiptUploadShared");

            DataFileHelper dFileHelper = new DataFileHelper(this);
            StringBuilder tempMSG = new StringBuilder();
            int tmpFileCount = 0;
            while (tmpIntFrom <= tmpIntTo) {
                int intFromStep = tmpIntFrom;
                Date fromDateStep = tmpCalendarFrom.getTime();
                String downtime = Format.Date8Format.format(tmpCalendarFrom.getTime());
                tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
                //加1天，后面不能再用tmpIntFrom
                tmpIntFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));

                String dataFilePath = dFileHelper.getBankReceiptDataFile(fromDateStep, p_reqReceipt.actNum);
                File dataFile = new File(dataFilePath);
                if (dataFile.exists()) {
                    WriteBankLogLn(intFromStep + "的回单已执行过下载，如需重新获取，请删除文件" + dataFilePath);
                    retAts.respCode = "0";
                    retAts.respInfo = intFromStep + "的回单已执行过下载";
                    tempMSG.append(" ").append(intFromStep).append("的回单已执行过下载");
                    continue;
                }
                WriteBankLogLn("开始执行" + intFromStep + "的回单文件下载");
                String downFile = getBankConfig().getValueAsString("receiptPrefix","Receipt_") + downtime + ".zip";
                String localDir = getTempFileDirectory();
                //String localDir = "D:\\WorkSpace\\IDEA\\dsp\\dsp-service\\src\\main\\tempfile\\201907\\05\\SPDB01";
                boolean isDownFileSucc = false;
                String localSavePath = localDir + File.separator + intFromStep;
                WriteBankLogLn("开始下载服务器文件- [" + downFile + "],至本地- [" + localSavePath + "].");
                String[] tmpEndRet = downFileFromBank(downFile, localSavePath);
                //String[] tmpEndRet = new String[]{"",""};
                if (tmpEndRet[0].length() == 0) {
                    WriteBankLogLn("文件下载已完成，开始解压...");
                    WriteBankLogLn("解压至：[" + localDir + "]");
                    ZipHelper.unzipFile(localSavePath + File.separator + downFile, localDir + File.separator + intFromStep);
                    WriteBankLogLn("文件解压已完成.");
                    File depressDir = new File(localDir);
                    if (depressDir.exists()) {
                        File[] deFiles = depressDir.listFiles();
                        if (deFiles != null && deFiles.length > 0) {
                            isDownFileSucc = true;
                        } else {
                            tmpEndRet[1] = "解压后文件夹" + localDir + "下为空";
                            continue;
                        }
                    } else {
                        tmpEndRet[1] = "解压后文件夹" + localDir + "不存在";
                        continue;
                    }
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = tmpEndRet[1];
                    tempMSG.append(" ").append(intFromStep).append("的回单下载失败,请重新下载 原因: ").append(tmpEndRet[1]);
                    WriteBankLogLn(intFromStep + "的回单下载失败,请重新下载 原因: " + tmpEndRet[1]);
                }
                if (isDownFileSucc) {
                    File receiptDir = new File(localDir + File.separator + intFromStep + File.separator + getBankConfig().getValueAsString("receiptPrefix","Receipt_") + downtime);
                    //File receiptDir = new File(localDir + File.separator + intFromStep + File.separator + "Receipt_20190331");
                    if (receiptDir.exists()) {
                        ReceiptFileSaveHelper saveHelper = new ReceiptFileSaveHelper(this);
                        if (!saveHelper.checkSet(this.sbLog, "310")) {
                            retAts.respCode = "-1";
                            retAts.respInfo = sbLog.toString();
                            retAts.writeRetToATS();
                            return retAts;
                        }
                        String destPath = receiptDir.getAbsolutePath();
                        String[] parentFile = FileHelper.listFiles(destPath);
                        for (String pfile : parentFile) {
                            String[] files = FileHelper.listFiles(destPath + File.separator + pfile);
                            if (files == null) {
                                WriteBankLogLn("解压后文件夹" + destPath + "下为空");
                            }
                            for (String file : files) {
                                String localRecipt = destPath + File.separator + pfile + File.separator + file;
                                if ((file.endsWith(".PDF") || file.endsWith(".pdf"))) {
                                    int result = -1;
                                    String tmpByDate = Format.Date8Format.format(new Date());
                                    tmpByDate = tmpByDate.substring(0, 6) + "/" + tmpByDate.substring(6, 8) + "/"
                                            + reqHeader.bankCode + "/" + p_reqReceipt.actNum + "/";
                                    if ("localhost".equals(SmbFileUtil.getUploadType())) {//上传到本地目录
                                        String shareDir = StringHelper.trimEndFileSp(FGBiz.dspCenter.dspSet.receiptShareDir.split("@")[1]) + File.separator;
                                        WriteBankLogLn("正在上传文件至本地共享目录:" + shareDir);
                                        result = FileHelper.copyFile(localRecipt, shareDir + tmpByDate + file);
                                    } else {//上传到共享文件夹
                                        if (new File(localRecipt).exists()) {
                                            WriteBankLogLn(
                                                    "正在上传文件至共享目录:" + FGBiz.dspCenter.dspSet.receiptShareDir);
                                            result = SmbFileUtil.smbUploading(localRecipt, tmpByDate,
                                                    FGBiz.dspCenter.dspSet.receiptShareDir);
                                        }
                                    }
                                    if (result == 0 || result == 1) {
                                        if (result == 0) {
                                            WriteBankLogLn("文件上传成功");
                                            tmpFileCount++;
                                        } else {
                                            WriteBankLogLn("文件已存在共享目录无需重复上传");
                                        }
                                        //0764284135605168_20190331_999015160002_1_receipt.pdf
                                        String[] filenameSpliter = file.split("_");
                                        //可通过解析pdf内容读取字段  亦可通过文件名获取
                                        WriteBankLogLn("正在解析回单文件：" + localRecipt);
                                        String[] pdfStrArr = PdfGenerateUtil.readPDFTable(localRecipt, 1000, 800).split("\r\n");

                                        try {
                                            String receiptCode = "";
                                            if(pdfStrArr[0].trim().equals("上海浦东发展银行业务凭证/回单")){
                                                receiptCode = pdfStrArr[1].substring(pdfStrArr[1].indexOf("回单编号") + 5, pdfStrArr[1].indexOf("交易流水") - 1);
                                            }else if(pdfStrArr[0].trim().equals("上海浦东发展银行电子缴税付款凭证")){
                                                receiptCode = pdfStrArr[1].substring(pdfStrArr[1].indexOf("回单编号") + 5, pdfStrArr[1].indexOf("回单类型") - 1);
                                            }else{
                                                throw new RuntimeException();
                                            }
                                            // 推送数据给ATS处理
                                            json.append("{");
                                            json.append("\"actNum\":\"" + filenameSpliter[0] + "\",");
                                            json.append("\"actCur\":\"" + p_reqReceipt.actCur + "\",");
                                            json.append("\"receiptCode\":\"" + receiptCode + "\",");
                                            json.append("\"receiptType\":\"" + "" + "\",");
                                            json.append("\"receiptState\":\"" + "" + "\",");
                                        /*if (filenameSpliter[0].equals(pdfStrArr[25])) {
                                            json.append("\"oppActName\":\"" + pdfStrArr[16] + "\",");
                                            json.append("\"oppActNum\":\"" + pdfStrArr[27].split("：")[1] + "\",");
                                            json.append("\"moneyway\":\"" + "2" + "\",");
                                        } else {
                                            json.append("\"oppActName\":\"" + pdfStrArr[28] + "\",");
                                            json.append("\"oppActNum\":\"" + pdfStrArr[25] + "\",");
                                            json.append("\"moneyway\":\"" + "1" + "\",");
                                        }*/
                                            //由于浦发银行这边存在两种情况的回单文件，然后从pdf文件取值时，无法通过位置来确认每个参数的值
                                            String amountStr = getAmountStr(pdfStrArr);
                                            json.append("\"amount\":\"" + amountStr + "\",");
                                            json.append("\"tranSeqNo\":\"" + filenameSpliter[2] + "\",");
                                            json.append("\"tranCode\":\"" + "" + "\",");
                                            json.append("\"tranDate\":\"" + Format.Date10Format.format(fromDateStep) + "\",");
                                            json.append("\"filePath\":\"" + tmpByDate
                                                    + StringHelper.getFileName(localRecipt) + "\",");
                                            json.append("\"fileType\":\"1\"");
                                            json.append("},");
                                        }catch (Exception ex){
                                            WriteBankLogLn("解析回单文件失败，请检查回单文件"+localRecipt+"内容是否正确。");
                                        }
                                    } else {
                                        retAts.respCode = "-1";
                                        retAts.respInfo = "上传文件至共享目录失败，请检查共享目录配置是否正确";
                                        //TODO单次失败和全部失败
                                        tempMSG.append(" ").append(intFromStep).append(":上传文件至共享目录失败，请检查共享目录配置是否正确");
                                        WriteBankLogLn(intFromStep + ":上传文件至共享目录失败，请检查共享目录配置是否正确 ");
                                        break;
                                    }
                                } else {//else文件名称错误
                                    WriteBankLogLn("文件名不符合要求.");
                                }
                            }
                        }
                    } else {
                        retAts.respCode = "-1";
                        retAts.respInfo = "不存在回单目录:" + receiptDir.getName();
                        tempMSG.append(" ").append(intFromStep).append(":不存在回单目录:").append(receiptDir.getName());
                        WriteBankLogLn(intFromStep + ":不存在回单目录:" + receiptDir.getName() + " ");
                        continue;
                    }
                }
            }
            WriteBankLogLn("成功保存了" + tmpFileCount + "个文件");
            retAts.respCode = "0";
            retAts.respInfo = "成功保存了" + tmpFileCount + "个文件" + tempMSG;
            WriteBankLogLn("成功保存了" + tmpFileCount + "个文件" + tempMSG);
            json.append("]}");
            if (tmpFileCount > 0) {
                String[] data = sendToATS(json.toString());
                if (data[0].length() == 0 && "ok".equals(data[1])) {
                    retAts.respCode = "0";
                    retAts.respInfo = "推送数据到ATS成功,请查看数据";
                    WriteBankLogLn("推送数据到ATS成功,请查看数据");
                } else {
                    retAts.respCode = "0";
                    retAts.respInfo = "推送数据到ATS失败";
                    WriteBankLogLn("推送数据到ATS失败");
                }
            }

        } catch (Exception ex) {
            ex.printStackTrace();
            retAts.respCode = "-1";
            retAts.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }
        retAts.writeRetToATS();
        return retAts;
    }

}
